#include "TCPSocket.h"
#include "socketAdaptor.h"
#include <string.h>

using namespace std;

SSLInitializer TCPSocket::m_ssl_init;


TCPSocket::TCPSocket(ISocketHandler & h) : 
	Socket(h),
	m_ssl_ctx(NULL),
	m_ssl(NULL),
	m_sbio(NULL),
	r(Reader(this)),
	w(Writer(this))
{
}


TCPSocket(TCPSocket & t) {
}


TCPSocket::~TCPSocket() {
	if (m_ssl) {
		SSL_free(m_ssl);
	}
}


bool TCPSocket::Open(std::string & serverName, int port) {
	return Open(serverName.c_str(), port);
}


bool TCPSocket::Open(const char * serverName, int port) {
	struct sockaddr_in servaddr;
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	struct hostent *he = gethostbyname( serverName );
	if( !he) {
		return false;
	}
	memcpy(&servaddr.sin_addr, he -> h_addr, sizeof(servaddr.sin_addr));

	servaddr.sin_port = htons(port);
	SOCKET s = CreateSocket(AF_INET, SOCK_STREAM, "tcp");
	if( connect(s, (struct sockaddr *) &servaddr, sizeof(servaddr)) != 0) {
		closesocket(s);
		return false;
	}
	Attach(s);
	initIOStream();
	return true;
}


void TCPSocket::initIOStream() {
	ISTREAM_ADAPTOR(is, r); 
	OSTREAM_ADAPTOR(os, w); 
}
